import { CONFIG } from "@/constants";
import { GetProp, UploadProps } from "antd";
import { DefaultOptionType } from "antd/es/cascader";
import dayjs from "dayjs";
const dateFormat = 'YYYY-MM-DD'
//判断头像是否为base64
export const isBase64 = (str: string | null | undefined) => {
    if (!str) return
    return !!(str.includes("data:image") && str.includes(";base64,"));
}
//拼接前缀url
export const ImageUrl = (url: string | null) => {
    return isBase64(url) ? url : CONFIG.IMAGE_URL + url
}

export const downLoadFile = (url: string) => {
    window.location.href = CONFIG.IMAGE_URL + url
}

export const customFormat = (str: string, intl: any) => {
    try {
        return intl.formatMessage({
            id: str,
        });
    } catch (error) {
        return '';
    }
}

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
export const getBase64 = (file: FileType): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
    });
export const getBase64Callback = (img: FileType, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

export const formFormat = (val: IBuildForm.IDefault, formTtem: Array<IBuildForm.IDefault> | undefined) => {
    const tempVal = { ...val };
    if (Array.isArray(formTtem)) {
        formTtem.forEach(item => {
            if (item.type === "actionSheet") {
                const zhi = tempVal[item.key];
                if (Array.isArray(zhi)) {
                    tempVal[item.key] = zhi[zhi.length - 1]
                }
            }
            if (item.type === 'videos' || item.type === 'files' || item.type === 'images') {
                const zhi = tempVal[item.key];
                if (Array.isArray(zhi)) {
                    tempVal[item.key] = zhi.map(i => {
                        return { url: i.url ? i.url : i.response?.data?.url }
                    })
                }
            }
            if (item.type === 'picker') {
                const zhi = tempVal[item.key];
                if (zhi) {
                    tempVal[item.key] = dayjs(zhi).format(dateFormat)
                }
            }
        })
    }
    return tempVal
}


export const filterCity = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
        (option) =>
            (option.label as string)
                .toLowerCase()
                .indexOf(inputValue.toLowerCase()) > -1,
    );



export const toImages = (src: string | undefined): string => {
    if (!src) {
        return ''
    }
    return isBase64(src) ? src : CONFIG.IMAGE_URL + src
}
//判断是否为对象
export const isObject = (obj: any) => {
    return Object.prototype.toString.call(obj) === '[object Object]'
}
//用于组件cardReveal数据的处理
export const exitCard = (template = [], data = {}, intl) => {

    //判断传进来的模版是否为空
    if (template.length === 0 || !Array.isArray(template)) {
        return []
    }
    //判断是否为对象
    if (!isObject(data)) {
        return []
    }
    template.forEach((item, index) => {
        //根据key来找到对应的对象
        let arr = item.key.split('.')
        let obj = data;
        for (let i in arr) {
            if (['mergename'].indexOf(arr[i]) !== -1) {
                obj = obj[intl.formatMessage({ id: "item.city." + arr[i] })]
            } else if (['username', 'identity_name'].indexOf(arr[i]) !== -1) {
                obj = obj[intl.formatMessage({ id: "item.user." + arr[i] })]
            } else if (['title', 'con_text', 'name', 'content', 'desc', 'introduction', 'person_name',
                'goods_num', 'goods_weight', 'goods_volume', 'show_text', 'mode_value', 'company_name',
                'car_l', 'car_w', 'car_h', 'industry', 'skill', 'con', 'speed_ranking', 'price_ranking',
                'num_ranking'
            ].indexOf(arr[i]) !== -1) {
                obj = obj[intl.formatMessage({ id: "item." + arr[i] })]
            } else {
                obj = obj[arr[i]]
            }
        }
        //判断是否为数组（数组一定为图片）
        if (Array.isArray(obj)) {
            obj.forEach(it => {
                template[index].images.push(ImageUrl(it.url))
            })
        } else {
            //判断是否为图片
            if (item.isIcon) {
                obj.split(',').forEach(immma => template[index].images.push(ImageUrl(immma)))
            }
            //处理时间戳
            if (item.isTimer) {
                template[index].message = time("S", obj) || ''
            } else {
                template[index].message = obj || ''
            }

        }

    })
    return template
}
